package com.github.ginirohikocha.dbm.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.adapter.RecycleCartAdapter;
import com.github.ginirohikocha.dbm.adapter.RecycleProductsAdapter;
import com.github.ginirohikocha.dbm.dialog.NewOfferDialog;
import com.github.ginirohikocha.dbm.entity.Offer;
import com.github.ginirohikocha.dbm.entity.ProductsPrice;
import com.github.ginirohikocha.dbm.util.HttpUtil;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OffersActivity extends AppCompatActivity {

    private RelativeLayout newOffer;
    private RecyclerView offerRecycler;
    private RecycleProductsAdapter productsAdapter;//↖RecyclerViewAdapter
    private FloatingActionButton cartToggle;
    private Button confirm;
    private TextView totalPrice;

    private LinearLayout bottomSheet;
    private BottomSheetBehavior behavior;//↖BottomSheetBehavior
    private RecyclerView cartRecycler;
    private RecycleCartAdapter cartAdapter;//↖RecyclerViewAdapter

    private ZLoadingDialog dialog;

    private String orderNum;
    @Deprecated
    private List<ProductsPrice> products;
    private List<Offer> offers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offers);
        setLoading(true);
        orderNum = getIntent().getStringExtra("orderNum");
        dialog = new ZLoadingDialog(OffersActivity.this);//加载动画
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.BLACK)//颜色
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .setHintText("加载中...");

        offerRecycler = findViewById(R.id.activity_offer_recycler);
        confirm = findViewById(R.id.fragment_offer_confirm);
        totalPrice = findViewById(R.id.fragment_offer_totalPrice);
        newOffer = findViewById(R.id.activity_offer_new);
        bottomSheet = findViewById(R.id.activity_offer_bottomSheet);
        behavior = BottomSheetBehavior.from(bottomSheet);
        cartToggle = findViewById(R.id.fragment_offer_cart);
        cartRecycler = findViewById(R.id.dialog_cart_recycler);
        cartToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (behavior.getState()) {
                    case BottomSheetBehavior.STATE_COLLAPSED:
                        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                        break;
                    default:
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                }
            }
        });

        //监听绑定
        newOffer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewOfferDialog newOfferDialog = new NewOfferDialog(OffersActivity.this, orderNum, offers);
                newOfferDialog.show();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateOffers();
            }
        });

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                getOffersData();
            }
        }, 500);
    }

    /**
     * 初始化列表，没有必要不需要被调用第二次
     * **/
    private void initRecycleAdapter() {
        productsAdapter = new RecycleProductsAdapter(OffersActivity.this, offers, orderNum);
        LinearLayoutManager layoutManager = new LinearLayoutManager(OffersActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        offerRecycler.setLayoutManager(layoutManager);
        offerRecycler.setAdapter(productsAdapter);
    }

    /**
     * 初始化购物车
     * **/
    private void initCart() {
        cartAdapter = new RecycleCartAdapter(OffersActivity.this, offers);
        LinearLayoutManager layoutManager = new LinearLayoutManager(OffersActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        cartRecycler.setLayoutManager(layoutManager);
        cartRecycler.setAdapter(cartAdapter);
        refresh();
    }

    private void getOffersData() {
        //查询订单业务
        JSONObject queryOffers = new JSONObject();
        queryOffers.put("orderNum", orderNum);

        HttpUtil.sendOkHttpPostRequest(Address.OFFER_QUERY, RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), queryOffers.toJSONString()), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                setLoading(false);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                final JSONObject json = JSONObject.parseObject(responseBody);
                try {
                    offers = json.getJSONArray("offers").toJavaList(Offer.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initRecycleAdapter();
                            initCart();
                            setLoading(false);
                        }
                    });
                } catch (NullPointerException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setLoading(false);
                        }
                    });
                    finish();
                }
            }
        });
    }

    @Deprecated
    private void getProductsData() {
        //查询产品单价
        JSONObject queryProducts = new JSONObject();
        HttpUtil.sendOkHttpPostRequest(Address.PRODUCTS_PRICE_QUERY, RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), queryProducts.toJSONString()), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                final JSONObject json = JSONObject.parseObject(responseBody);
                products = json.getJSONArray("productsPrice").toJavaList(ProductsPrice.class);
            }
        });
    }

    private void updateOffers() {
        setLoading(true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNum", orderNum);
        jsonObject.put("offers", JSON.toJSONString(offers));

        final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());

        HttpUtil.sendOkHttpPostRequest(Address.OFFER_UPDATE, requestBody, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.w("更新业务", "网络异常");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setLoading(false);
                        Toast.makeText(OffersActivity.this, "网络异常，提交失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = response.body().string();
                Log.w("更新业务", responseBody);
                JSONObject res = JSONObject.parseObject(responseBody);
                setLoading(false);
                if (res.getBoolean("succ")) {
                    setResult(RESULT_OK);
                    finish();
                } else {
                    Toast.makeText(OffersActivity.this, "数据错误，提交失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void refresh() {
        if (productsAdapter != null) {
            totalPrice.setText(String.format(Locale.CHINESE, "%.2f", productsAdapter.getPriceCount()));
        }
        if (cartAdapter != null) {
            cartAdapter.refresh();
        }
    }

    public void setLoading(boolean b) {
        if (b) {
            dialog.show();
        } else {
            dialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        setLoading(false);
        super.onDestroy();
    }
}
